<template>
  <!-- <div class="avatar-root"> -->
  <v-btn
    class="avatar-border"
    icon
    x-large
    :disabled="mode == 0"
    @click="clickAction"
  >
    <v-avatar :size="getAvatarSize">
      <img
        v-if="url != undefined && url != null && url != ''"
        alt="Avatar"
        :src="url"
      />
      <v-icon v-else color="red">mdi-account</v-icon>
    </v-avatar>

    <input
      type="file"
      id="file-uploader"
      accept="image/*"
      v-show="false"
      @change="uploadPic"
  /></v-btn>
  <!-- </div> -->
</template>

<script>
export default {
  name: "Avatar",
  data() {
    return {
      url: "",
    };
  },
  created() {
    if (this.src === "") {
      this.url = this.$store.getters.getCurrUserAvatar;
    } else {
      this.url = this.src;
    }
  },
  props: {
    mode: {
      type: Number,
      default: 0, // 0 for display  1 for edit
    },
    size: {
      type: Number,
      default: 36,
    },
    src: {
      type: String,
      default: "",
    },
  },
  computed: {
    getAvatarSize() {
      return this.size + "px";
    },
  },
  methods: {
    clickAction() {
      if (this.mode == 1) {
        document.getElementById("file-uploader").click();
      }
    },
    uploadPic(e) {
      if (e.target.files === null || e.target.files.length === 0) return;
      var file = e.target.files[0];
      if (file != null) {
        //图片接口
        this.$fileService.uploadFile(file, (result) => {
          if (result.success) {
              this.$api.resource.register({
                  user_id: this.$store.getters.getUserId,
                  avatar_url: result.url
              }).then((res)=>{
                  if(res.success){
                      this.url = result.url;
                      this.$store.commit("setAvatar",result.url);
                  }else {
                      this.$Message.error("上传失败："+result.exc);
                  }
              }).catch((e)=>{
                  this.$Message.error("图片上传错误: "+ e)
              })
            
          } else this.$Message.error("图片上传错误: " + result.exc);
        });
      }
    },
  },
};
</script>
<style>
.avatar-border {
  border-radius: 50%;
  border: 1px solid grey;
}
</style>
